<template>
    <div class="div-view-search">
        <el-row gutter="20" class="search">
            <el-col :span="4">
                <el-select v-model="selectedType" placeholder="选择定制官账号状态" @change="handleFilterChange"
                    class="filter-select">
                    <el-option label="所有状态" value=""></el-option>
                    <el-option label="已通过" value="0"></el-option>
                    <el-option label="待审核" value="1"></el-option>
                    <el-option label="未通过" value="2"></el-option>
                </el-select>
            </el-col>

            <el-col :offset="14" :span="4">
                <el-input v-model="searchName" placeholder="请输入定制官" />
            </el-col>
            <el-col :span="2">
                <el-button type="primary" @click="handleSearch">查询</el-button>
            </el-col>
        </el-row>
    </div>
    <div class="div-view">
        <!-- 表格 -->
        <div class="table">
            <el-table :data="sortedServicedesigners" :header-cell-style="{ backgroundColor: '#f0f0f0' }"
                style="width: 100%" @sort-change="handleSortChange">

                <el-table-column property="designerId" label="定制官ID" />
                <el-table-column property="userId" label="关联用户ID" />

                <!-- 修改资质证明文件列 -->
                <el-table-column label="资质证明文件">
                    <template #default="scope">
                        <!-- 判断是否有 PDF 链接 -->
                        <a v-if="scope.row.designerQualification"
                            @click.prevent="handleDownloadPDF(scope.row.designerId)" href="#">
                            下载资质证明
                        </a>
                        <span v-else>暂无资质证明</span>
                    </template>
                </el-table-column>

                <el-table-column property="applyingTime" label="申请时间" />

                <el-table-column property="qualifyStatus" label="验证状态">
                    <template #default="scope">
                        <span class="status-container">
                            <el-icon size="20">
                                <CircleCheck :class="getStatusIconClass(scope.row.qualifyStatus)" />
                            </el-icon>
                            <span>{{ getStatusText(scope.row.qualifyStatus) }}</span>
                        </span>
                    </template>
                </el-table-column>

                <!-- 操作按钮 -->
                <el-table-column width="250" label="操作">
                    <template #default="{ row }">
                        <!-- 驳回申请按钮，仅当状态为1（待审核）时可点击 -->
                        <el-button type="danger" @click="handleRejectApplication(row)"
                            :disabled="row.qualifyStatus !== 1" link>
                            驳回申请
                        </el-button>
                        <!-- 取消资格按钮，仅当状态为0（已通过）时可点击 -->
                        <el-button type="primary" @click="handleCancelQualification(row)"
                            :disabled="row.qualifyStatus !== 0" link>
                            取消资格
                        </el-button>
                        <!-- 通过审核按钮，仅当状态为1（待审核）时可点击 -->
                        <el-button type="success" @click="handleApproveApplication(row)"
                            :disabled="row.qualifyStatus !== 1" link>
                            通过审核
                        </el-button>
                    </template>
                </el-table-column>

            </el-table>
        </div>

        <!-- 分页 -->
        <div class="demo-pagination-block">
            <el-pagination v-model:currentPage="pageNum" v-model:pageSize="pageSize" :page-sizes="[5, 10, 15, 20]"
                layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                style="display: flex; justify-content: flex-end; margin-top: 10px;" />
        </div>
    </div>

</template>

<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue';
import axios from 'axios';
import { ElMain, ElMessage } from 'element-plus';


// 定义分页数据
const pageNum = ref(1);
const pageSize = ref(5);
// 定义总数据量
const total = ref(0);
const searchName = ref('');
//定义数据数组
const tableData = ref([]);
// 定义选中的下拉框值
const selectedType = ref('');
// 获取数据的函数
const fetchData = async () => {
    try {
        const response = await axios.get('http://localhost:8088/servicedesigners/filter', {
            params: {
                qualifyStatus: selectedType.value,
            },
        });
        tableData.value = response.data.servicedesigners;
    } catch (error) {
        console.error('查询失败:', error);
    }
};
// 当前排序的属性和顺序
const sortProp = ref('');
const sortOrder = ref(''); // 'ascending' 或 'descending'
const sortedServicedesigners = computed(() => {
    return tableData.value.slice().sort((a, b) => {
        if (sortProp.value === 'applyingTime') {
            const timeA = new Date(a.applyingTime).getTime();
            const timeB = new Date(b.applyingTime).getTime();
            return sortOrder.value === 'ascending' ? timeA - timeB : timeB - timeA;
        }
        return 0;
    });
});
// 处理排序变化的函数
const handleSortChange = (newSortInfo) => {
    sortProp.value = newSortInfo.prop;
    sortOrder.value = newSortInfo.order;
};
// 处理下拉框变化的函数
const handleFilterChange = () => {
    fetchData();
};

// 下载 PDF 方法
const handleDownloadPDF = async (designerId) => {
    try {
        console.log(`开始请求签名 URL，designerId: ${designerId}`);
        getData();
        // 请求后端接口获取签名 URL
        const response = await axios.get(`/getQualificationPath`, {
            params: { designerId, timestamp: new Date().getTime() }, // 加入时间戳确保每次请求都是新请求
        });

        console.log(`签名 URL 请求成功，返回数据:`, response.data);

        const signedUrl = response.data;  // 获取签名 URL
        console.log(`签名 URL：`, signedUrl);

        if (!signedUrl) {
            throw new Error("未能获得有效的签名 URL");
        }

        // 使用签名 URL 触发文件下载
        const a = document.createElement('a');
        a.href = signedUrl;
        a.download = 'qualification1.pdf';  // 可以指定下载的文件名
        document.body.appendChild(a);
        a.click();  // 触发下载
        document.body.removeChild(a);
        console.log("下载请求已发出");

    } catch (error) {
        console.error("下载失败：", error);
        ElMessage.error("文件下载失败，请稍后重试！");
    }
};

const getData = async () => {
    try {
        const response = await axios.get('http://localhost:8088/servicedesigners/getByPage', {
            params: {
                pageNum: pageNum.value,
                pageSize: pageSize.value,
            },
        });
        tableData.value = response.data.records;
        total.value = response.data.total;
        pageNum.value = response.data.current;
        pageSize.value = response.data.size;
    } catch (error) {
        console.error('跳转失败:', error);
    }
};
// 当前页或每页数量改变时重新获取数据
const handleSizeChange = () => {
    getData();
};
const handleCurrentChange = () => {
    getData();
};

const handleSearch = async () => {
    try {
        const response = await axios.get('http://localhost:8088/servicedesigners/getByID',
            { params: { designerId: searchName.value } });
        tableData.value = response.data;
    } catch (error) {
        console.error('查找出错:', error);
    }
};

// 更新操作的函数
const updateServicedesignersStatus = async (designerId, qualifyStatus) => {
    try {
        // 构建包含ID和新状态的请求体
        const requestBody = {
            designerId,
            qualifyStatus,
        };

        const response = await axios.put(
            "http://localhost:8088/servicedesigners/update",
            requestBody
        );

        if (response.data) {
            ElMessage.success("更新成功");
            // 同步更新表格中的数据状态
            const servicedesigners = tableData.value.find((item) => item.designerId === designerId);
            if (servicedesigners) {
                servicedesigners.qualifyStatus = qualifyStatus;
            }
        }
        return response.data;
    } catch (error) {
        console.error("更新失败:", error);
        ElMessage.error("更新失败");
        return null;
    }
};

// 0已通过 1待审核 2未通过
// 驳回申请 1-->2
// 通过申请 1-->0
// 取消资格 0-->2
// 驳回申请
const handleRejectApplication = (row) => {
    updateServicedesignersStatus(row.designerId, 2); // 改为状态2表示驳回
};

// 取消资格
const handleCancelQualification = (row) => {
    updateServicedesignersStatus(row.designerId, 2); // 改为状态2表示取消资格
};

// 通过审核
const handleApproveApplication = (row) => {
    updateServicedesignersStatus(row.designerId, 0); // 改为状态0表示通过审核
};



// 组件挂载后获取初始数据
onMounted(() => {
    fetchData();
    getData();
});

//处理状态栏样式
function getStatusIconClass(qualifyStatus) {
    switch (qualifyStatus) {
        case 0:
            return 'status-icon-green';
        case 1:
            return 'status-icon-red';
        case 2:
            return 'status-icon-gray';
    }
}
function getStatusText(qualifyStatus) {
    switch (qualifyStatus) {
        case 0:
            return '已通过';
        case 1:
            return '待审核';
        case 2:
            return '未通过';
    }
}

</script>

<style scoped>
.div-view {
    background-color: #fff;
    padding: 10px 10px;
    /* 内边距 */
    border-radius: 5px;
    /* 圆角 */
    margin-bottom: 10px;
    /* 下边距 */
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    /* 阴影 */
}

.div-view-search {
    background-color: #fff;
    padding: 10px 10px;
    /* 内边距 */
    border-radius: 5px;
    /* 圆角 */
    margin-bottom: 10px;
    /* 下边距 */
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    /* 阴影 */
}

.demo-pagination-block+.demo-pagination-block {
    margin-top: 10px;
}

.demo-pagination-block .demonstration {
    margin-bottom: 16px;
}

/* 图标特定类，仅用于图标 */
.status-icon-green {
    color: green;
    margin-right: 5px;
    /* 图标和文本之间的间距 */
}

.status-icon-red {
    color: red;
    margin-right: 5px;
}

.status-icon-gray {
    margin-right: 5px;
    color: gray;
}
</style>